package com.frogs.ucenter.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.jsoup.Connection.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.PageTurn;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.web.api.entity.ApiUrl;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.ucenter.service.AbsService;
import com.frogs.ucenter.service.IntegralService;

@Service("integralServie")
public class IntegralServiceImpl extends AbsService implements IntegralService{

	private static Logger log = LoggerFactory.getLogger(IntegralServiceImpl.class);
	
	@Override
	public PageList<Map<String,Object>> getIntegralCouponList(Integer type, Integer columnId , Integer isVip, Integer pageNo, Integer pageSize) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("INTEGRAL_EXCHANGE_LIST");
		String[] otherParams = {ApiUrlParamEnum.type.getParamName(), type.toString(),
				ApiUrlParamEnum.sectionCode.getParamName(), columnId.toString(),
				ApiUrlParamEnum.pageNo.getParamName(), pageNo.toString(),
				ApiUrlParamEnum.pageSize.getParamName(), pageSize.toString(), 
				ApiUrlParamEnum.isVip.getParamName(), isVip.toString() };
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		PageList<Map<String,Object>> result = new PageList<Map<String,Object>>();
		JSONObject jsonObjectResult = null;
		try{
			jsonObjectResult = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() == jsonObjectResult.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
				JSONArray listJSONArray = jsonObjectResult.getJSONObject("response").getJSONArray("list");
				List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
				if (listJSONArray != null && listJSONArray.size() > 0) {
					Map<Integer, JSONObject> cardMap = this.getCardMap(listJSONArray);
					list = this.mergeCoupon(listJSONArray, cardMap);
				}
				result.addAll(list);
				
		    	JSONObject pageTurnJSONObject = jsonObjectResult.getJSONObject("response").getJSONObject("pageTurn");
		    	result.setPageTurn(JSON.toJavaObject(pageTurnJSONObject, PageTurn.class));
			}
		} catch (IllegalStateException e) {
			log.error("func[getIntegralCouponList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("获取积分优惠券列表接口请求失败！");
		}
		return result;
	}
	
	@Override
	public JSONObject userIntegralCouponExchange(Integer userId, Integer id)
			throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_INTEGRAL_COUPON_EXCHANGE");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.id.getParamName(), id.toString(),
				};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
		} catch (IllegalStateException e) {
			log.error("func[getUserIntegralInfo] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("积分兑换优惠券接口请求失败！");
		}
		
		return result;
	}
	
	/**
	 * 拼凑cardId串
	 * @return
	 */
	private String getCardIds(JSONArray listJSONArray){
		StringBuilder sb = new StringBuilder(); 
		for(int i= 0;i<listJSONArray.size() ;i++){
			JSONObject listJSONObject = (JSONObject)listJSONArray.get(i);
			sb.append(listJSONObject.getInteger("relationId"));
			if(i < listJSONArray.size()-1)
				sb.append(",");
		}
		return sb.toString();
	}
	
	protected Map<Integer,JSONObject> getCardMap(JSONArray listJSONArray) throws Exception {
    	String cardIds = this.getCardIds(listJSONArray);
    	JSONObject cardList = this.getCouponListByCardIds(cardIds);
		JSONArray cardArrayJson = cardList.getJSONObject("response").getJSONArray("list");
    	Map<Integer,JSONObject> cardMap = new HashMap<Integer,JSONObject>();
    	if(null != cardArrayJson ) {
    		for(Object cardObject:cardArrayJson){
    			JSONObject card = (JSONObject)cardObject;
    			cardMap.put(card.getInteger("id"), card);
    		}
		}
    	return  cardMap;
    }
	
	protected List<Map<String,Object>> mergeCoupon(JSONArray jsonArray, Map<Integer,JSONObject> cardMap){
    	List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		for(int j = 0; j<jsonArray.size(); j++) {
			JSONObject jsonObject = jsonArray.getJSONObject(j);
			try{
				JSONObject cardJSONObject = cardMap.get(jsonObject.getInteger("relationId"));
				Map<String,Object> infoMapObject= JSON.toJavaObject(jsonObject, Map.class);
				infoMapObject.put("title", cardJSONObject.getString("title") );
				infoMapObject.put("reduceValue",cardJSONObject.getDouble("reduceValue") );
				infoMapObject.put("leastCost",cardJSONObject.getDouble("leastCost") );
				infoMapObject.put("maxCount",cardJSONObject.getInteger("maxCount") );
				infoMapObject.put("bindCount",cardJSONObject.getInteger("bindCount") );
				infoMapObject.put("imgUrl",cardJSONObject.getString("imgUrl") );
				list.add(infoMapObject);
			}
			catch(Exception e){
				log.error("func[mergeCoupon] relationId[{}] is null",
						new Object[] { jsonObject.getInteger("relationId") });
			}
		}
		return list;
    }
	
	public JSONObject getCouponListByCardIds(String ids) throws Exception {
		ApiUrl apiUrl = this.buildPromotionApiBaseUrl("PROMOTION_CARD_LIST_BY_IDS");
		String[] otherParams = {ApiUrlParamEnum.couponIds.getParamName(), ids,
				ApiUrlParamEnum.couponId.getParamName(), "1",
				ApiUrlParamEnum.pageNo.getParamName(), "1",
				ApiUrlParamEnum.pageSize.getParamName(), "12",
				ApiUrlParamEnum.applicablePlatformId.getParamName(), "3"
		};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[getIntegralCouponList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("获取优惠券列表接口请求失败！");
		}
		return result;
	}
	
	/* 
	 * 积分兑换激活码
	 */
	@Override
	public JSONObject cdkeyExchange(Integer userId, Integer id,
			String expandCode, Integer applicablePlatformId)
			throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_INTEGRAL_CDKEY_EXCHANGE");
		String[] otherParams = {
				ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.id.getParamName(), id.toString(),
				ApiUrlParamEnum.expandCode.getParamName(), expandCode,
				ApiUrlParamEnum.applicablePlatformId.getParamName(), applicablePlatformId.toString(),
				
				};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
		} catch (IllegalStateException e) {
			log.error("func[cdkeyExchange] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("积分兑换保险接口请求失败！");
		}
		
		return result;
	}
}
